package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.DishMapper;
import com.itheima.pojo.Dish;
import com.itheima.pojo.DishDto;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish>implements DishService {
    @Autowired
    private DishFlavorService flavorService;
    @Override
    public Integer saveWithFlavor(DishDto dto) {
        ArrayList<DishFlavor> list= (ArrayList<DishFlavor>) dto.getFlavors();
        boolean save = this.save(dto);
        Long id=dto.getId();
        for (int i=0;i<list.toArray().length;i++){
            list.get(i).setDishId(id);
        }
        System.out.println(list);
        boolean b = flavorService.saveBatch(list);
        if(save&&b){
            return 1;
        }else {
            return 0;
        }
    }
@Transactional
    @Override
    public Integer updateWithFlavor(DishDto dishDto) {
        boolean save = this.updateById(dishDto);
        LambdaQueryWrapper<DishFlavor> lqw=new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,dishDto.getId());
        flavorService.remove(lqw);
        ArrayList<DishFlavor> list= (ArrayList<DishFlavor>) dishDto.getFlavors();
        Long id=dishDto.getId();
        for (int i=0;i<list.toArray().length;i++){
            list.get(i).setDishId(id);
        }
        boolean b = flavorService.saveBatch(list);
        if(save&&b){
            return 1;
        }else {
            return 0;
        }
    }
}
